import pygame
import math
import time
from GameLogic import game_logic

black_chess = pygame.image.load("black_piece.png")
white_chess = pygame.image.load("white_piece.png")
all_chesses = pygame.sprite.Group()
chess_state = [[0 for i in range(0, 15)] for j in range(0, 15)]
NO_WINNER = pygame.USEREVENT + 1
HUMAN_WIN = pygame.USEREVENT + 2
MACHINE_WIN = pygame.USEREVENT + 3
no_winner = pygame.event.Event(NO_WINNER)
human_win = pygame.event.Event(HUMAN_WIN)
machine_win = pygame.event.Event(MACHINE_WIN)


class Chess(pygame.sprite.Sprite):
    def __init__(self, color, pos):
        super().__init__()
        if color == "black":
            self.image = pygame.transform.scale(black_chess, (35, 35))
        else:
            self.image = pygame.transform.scale(white_chess, (35, 35))
        self.rect = self.image.get_rect()
        self.rect.centerx = 30 + 50 * pos[0]
        self.rect.centery = 30 + 50 * pos[1]


def chess_creator(pos, color):
    if color == "white":
        chess_state[pos[0]][pos[1]] = 1
    else:
        chess_state[pos[0]][pos[1]] = 2
    new_chess = Chess(color, pos)
    all_chesses.add(new_chess)


def game_reset():
    pygame.event.clear()
    global chess_state, all_chesses
    chess_state = [[0 for i in range(0, 15)] for j in range(0, 15)]
    all_chesses.empty()


def win_lose_judge(color):
    global chess_state
    # 分类，如果是人下完那么判断人（白），如果是机器下完那么判断机器（黑）。
    color_mark = 0
    if color == "white":
        color_mark = 1
    else:
        color_mark = 2

    for i in range(0, 15):
        for j in range(0, 15):
            if chess_state[i][j] == color_mark:
                if single_win_check([i, j]):
                    if color_mark == 1:
                        pygame.event.post(human_win)
                    if color_mark == 2:
                        pygame.event.post(machine_win)
    return


def single_win_check(pos):
    possible_directions = []
    if pos[1] >= 4:
        possible_directions.append([0, -1])
    if pos[1] >= 4 and pos[0] <= 10:
        possible_directions.append([1, -1])
    if pos[0] <= 10:
        possible_directions.append([1, 0])
    if pos[0] <= 10 and pos[1] <= 10:
        possible_directions.append([1, 1])
    if pos[1] <= 10:
        possible_directions.append([0, 1])
    if pos[0] >= 4 and pos[1] <= 10:
        possible_directions.append([-1, 1])
    if pos[0] >= 4:
        possible_directions.append([-1, 0])
    if pos[0] >= 4 and pos[1] >= 4:
        possible_directions.append([-1, -1])
    for direct in possible_directions:
        if single_direction_win(pos, direct):
            return True
    return False


def single_direction_win(pos, direction):
    global chess_state
    x = direction[0]
    y = direction[1]
    return chess_state[pos[0]][pos[1]] == chess_state[pos[0] + x][pos[1] + y] and \
        chess_state[pos[0] + x][pos[1] + y] == chess_state[pos[0] + 2 * x][pos[1] + 2 * y] and \
        chess_state[pos[0] + 2 * x][pos[1] + 2 * y] == chess_state[pos[0] + 3 * x][pos[1] + 3 * y] and \
        chess_state[pos[0] + 3 * x][pos[1] + 3 * y] == chess_state[pos[0] + 4 * x][pos[1] + 4 * y]


def machine_put_new_chess():
    global chess_state
    return game_logic(chess_state)


def isfull():
    global chess_state
    for i in range(0, 15):
        for j in range(0, 15):
            if chess_state[i][j] == 0:
                return False
    return True


if __name__ == "__main__":
    # pygame setup
    pygame.init()
    screen = pygame.display.set_mode((760, 760))
    clock = pygame.time.Clock()
    running = True

    # 横向是x，纵向是y
    # 玩家是白，机器是黑
    while running:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_buttons = pygame.mouse.get_pressed(3)
                if mouse_buttons[0]:
                    # 按下左键下棋
                    mouse_position = pygame.mouse.get_pos()
                    relative_pos_from_board = [mouse_position[0] - 30, mouse_position[1] - 30]
                    new_chess_position = [math.floor((relative_pos_from_board[0] + 25) / 50),
                                          math.floor((relative_pos_from_board[1] + 25) / 50)]
                    if 0 <= new_chess_position[0] <= 14 and 0 <= new_chess_position[1] <= 14:
                        if chess_state[new_chess_position[0]][new_chess_position[1]] == 0:
                            chess_creator(new_chess_position, "white")
                            time.sleep(0.1)
                            win_lose_judge("white")
                            if isfull():
                                pygame.event.post(no_winner)
                            chess_creator(machine_put_new_chess(), "black")
                            time.sleep(0.1)
                            win_lose_judge("black")
                            if isfull():
                                pygame.event.post(no_winner)

                if mouse_buttons[1]:
                    # 1指的是鼠标中键
                    game_reset()

            if event.type == HUMAN_WIN:
                time.sleep(0.1)
                game_reset()

            if event.type == MACHINE_WIN:
                time.sleep(0.1)
                game_reset()

            if event.type == NO_WINNER:
                time.sleep(0.1)
                game_reset()

        screen.fill("burlywood")
        for i in range(0, 15):
            pygame.draw.line(screen, "black", (30, 30 + i * 50), (730, 30 + i * 50))
        for j in range(0, 15):
            pygame.draw.line(screen, "black", (30 + j * 50, 30), (30 + j * 50, 730))
        all_chesses.draw(screen)
        pygame.display.flip()

    pygame.quit()